function Bubble(right, flipped) {
    this.id = Bubble.id++;
    this.direction = right ? 'right' : 'left';
    this.flipped = !!flipped;
	this.choices = [];
}

Bubble.prototype = {
    onRender: function () {
        for (choice in this.choices) {
            this.choices[choice].onRender();
        }
    },

    render: function () {
        if (this.el) {
            return this.el;
        }

        var el;
        this.top = $('<div></div>');
        this.top.addClass('text-bubble-top');
        if (this.flipped) {
            this.top.addClass('text-bubble-left-top-flipped');
        }
        this.center = $('<div></div>');
        this.center.addClass('text-bubble-center');
        this.textEl = $('<div></div>');
        this.textEl.addClass('bubble-text');
        this.bottom = $('<div></div>');
        this.bottom.addClass('text-bubble-' + this.direction + '-bottom');
        if (this.flipped) {
            this.bottom.addClass('text-bubble-left-bottom-flipped');
        }
        el = $('<div></div>');
        el.addClass('text-bubble-' + this.direction);
        el.append(this.top);
        el.append(this.center);
        el.append(this.bottom);
        this.center.append(this.textEl);

        if (this.text) {
            this.textEl.html(this.text);
        }

        for (choice in this.choices) {
            this.center.append(this.choices[choice].render());
        }

        if (this.style) {
            el.css(this.style);
        }

        this.el = el;
        return el;
    },

    setText: function (text) {
        this.text = text;
        if (this.textEl) {
            this.textEl.html(text);
        }
    },

    addChoice: function (text, type, fn) {
        var choice;
        if (type === 'button') {
            choice = new Button(text, { fn: fn });
        } else {
            choice = new HyperLink(text, { fn: fn });
        }
        this.choices[this.choices.length] = choice;

        if (this.center) {
            this.center.append(choice.render());
            choice.onRender();
        }

        return choice;
    },

    addTextChoice: function (value, fn) {
        var choice = new TextField({ keyup: function (e) {
            if (e.keyCode == 13) {
                if (fn) {
                    fn();
                }
            }
        }
        });
        choice.value = value;
        this.choices[this.choices.length] = choice;

        if (this.center) {
            this.center.append(choice.render());
            choice.onRender();
        }

        return choice;
    },

    clearChoices: function () {
        for (choice in this.choices) {
            var el = this.choices[choice].el;
            if (el) {
                el.remove();
            }
        }
        this.choices = [];
    }
};

Bubble.id = 1;
